package com.example.silence.mypainter.All.Activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.silence.mypainter.R;
import com.larswerkman.holocolorpicker.ColorPicker;
import com.larswerkman.holocolorpicker.OpacityBar;
import com.larswerkman.holocolorpicker.SVBar;
import com.mxn.soul.flowingdrawer_core.FlowingDrawer;
import com.nightonke.boommenu.BoomButtons.OnBMClickListener;
import com.nightonke.boommenu.BoomButtons.TextInsideCircleButton;
import com.nightonke.boommenu.BoomMenuButton;
import com.nightonke.boommenu.Util;
import com.wangjie.rapidfloatingactionbutton.RapidFloatingActionButton;
import com.wangjie.rapidfloatingactionbutton.RapidFloatingActionHelper;
import com.wangjie.rapidfloatingactionbutton.RapidFloatingActionLayout;
import com.wangjie.rapidfloatingactionbutton.contentimpl.labellist.RFACLabelItem;
import com.wangjie.rapidfloatingactionbutton.contentimpl.labellist.RapidFloatingActionContentLabelList;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import deadline.statebutton.StateButton;

public class DrawActivity extends AppCompatActivity implements RapidFloatingActionContentLabelList.OnRapidFloatingActionContentLabelListListener {
    ////////矩形属性值
    private int rectangle_BorderWidth = 10;
    private int rectangle_Radius = 0;
    private Boolean isRecSolid = true;
    private Boolean isRecFilled = false;

    ////////画笔属性
    private int pen_Size = 10;
    private Boolean isPenIsSolid = true;

    ////////橡皮属性
    private int eraser_Size = 50;

    ////////直线属性
    private int line_Size = 10;
    private Boolean isLineSolid = true;

    ///////圆形属性
    private int cercle_BorderWidth = 10;
    private Boolean isCercleSolid = true;
    private Boolean isCercleFilled = false;
    private Boolean c_Or_e = true;

    ////////扇形属性
    private int sector_BorderWidth = 10;
    private Boolean isSectorSolid = true;
    private Boolean isSectorFilled = false;
    private Boolean isSectorClose = true;
    private int sector_Step = 0;
    private int centerX, centerY, sX, sY, eX, eY;
    private double sAngle, eAngle, dAngel;

    ////////曲线属性
    private int graph_Size = 10;
    private Boolean isGraphSolid = true;
    private int graph_Step = 0, gSX, gSY, gEX, gEY, cDX1, cDY1, cDX2, cDY2;

    ////////多边形属性
    private int polygon_Size = 10;
    private Boolean isPolygonSolid = true;
    private Boolean isPolygonFilled = false;
    private Point[] polPoint = new Point[100];
    private int pointNum = 0;

    ////////文字属性
    private int text_Size = 100, f_B_Size = 5;
    private Boolean isTextSolid = true;
    private Boolean isTextFilled = false;
    private String text_Content = "文本内容";

    private Boolean isSaved = false;

    private static final int REQUEST_CHOOSE_IMAGE = 0x01;

    private static final int REQUEST_WRITE_EXTERNAL_PERMISSION_GRANT = 0xff;

    private int width, height;//画布宽高

    private ImageView mImg, mImgTemp;//画布底和缓存画布底,第三层画布
    private ImageView pen, eraser, revoke, clean;
    private Bitmap mBm, mBmTemp;//画布
    private ArrayList<Object> hisList = new ArrayList<>();
    private Canvas mCv, mCvTemp;
    private Paint mPt_Fill, mPt_Border;
    private int toolNum = 0;
    private int fillColor = Color.BLUE, borderColor = Color.BLACK, fillColor2 = Color.BLUE, borderColor2 = Color.BLACK;//边框和填充颜色
    private Boolean fillGOrS = false, borderGOrS = false;//是否使用渐变色
    private LinearGradient linearGradient1, linearGradient2;
    private Boolean f_Or_B = false;
    private Path mPath;

    private BoomMenuButton menuButton;

    private StateButton openBt;
    private StateButton saveBt;

    private FlowingDrawer mFd;//侧栏菜单
    private RapidFloatingActionHelper rHep;

    private ImageButton bTYes, bTNo;

    @SuppressWarnings("FieldCanBeLocal")
    @SuppressLint("SdCardPath")
    private static String path = "/sdcard/SimplePainter";

    private String[] toolName = {"铅笔", "橡皮", "直线", "曲线", "矩形", "圆形", "多边形", "文字", "扇形"};

    private int[] toolId = {
            R.drawable.tool01,
            R.drawable.tool02,
            R.drawable.tool03,
            R.drawable.tool04,
            R.drawable.tool05,
            R.drawable.tool06,
            R.drawable.tool07,
            R.drawable.tool08,
            R.drawable.tool09
    };

    long startTime = 0;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_draw);

        mImg = findViewById(R.id.draw_paint);
        mImgTemp = findViewById(R.id.draw_paint_temp);
        mFd = findViewById(R.id.drawerlayout);
        menuButton = findViewById(R.id.tool_menu);//工具菜单
        pen = findViewById(R.id.pen_d);
        eraser = findViewById(R.id.eraser_d);
        revoke = findViewById(R.id.revoke_d);
        clean = findViewById(R.id.claen_d);
        bTYes = findViewById(R.id.yes);
        bTNo = findViewById(R.id.no);
        openBt = findViewById(R.id.open_d);
        saveBt = findViewById(R.id.save_d);

        StateButton aSbt = findViewById(R.id.about_p);
        StateButton newBt = findViewById(R.id.new_d);
        StateButton quitBt = findViewById(R.id.quit_d);
        StateButton mSbt = findViewById(R.id.menu_p);//菜单按钮
        RapidFloatingActionLayout rFal = findViewById(R.id.rfal);
        RapidFloatingActionButton rFbt = findViewById(R.id.rfab);
        TextView textView_Title = findViewById(R.id.title_p);
        TextView cBg = findViewById(R.id.color_bt_bg);
        RelativeLayout re_Tool = findViewById(R.id.tool_layout);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        bTYes.setVisibility(View.GONE);
        bTNo.setVisibility(View.GONE);

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        width = getIntent().getIntExtra("width", 0);
        height = getIntent().getIntExtra("height", 0);

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        Animation a1 = AnimationUtils.loadAnimation(DrawActivity.this, R.anim.d_top);
        Animation a2 = AnimationUtils.loadAnimation(DrawActivity.this, R.anim.d_tool);
        Animation a3 = AnimationUtils.loadAnimation(DrawActivity.this, R.anim.d_draw);
        Animation a4 = AnimationUtils.loadAnimation(DrawActivity.this, R.anim.d_lt);
        Animation a5 = AnimationUtils.loadAnimation(DrawActivity.this, R.anim.d_color);

        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        mSbt.setOnClickListener(new View.OnClickListener() {//打开侧栏菜单
            @Override
            public void onClick(View v) {
                mFd.openMenu();
            }
        });

        cBg.setOnClickListener(new View.OnClickListener() {//打开工具箱
            @Override
            public void onClick(View v) {
                menuButton.boom();
            }
        });

        newBt.setOnClickListener(new View.OnClickListener() {//新建画布
            @Override
            public void onClick(View v) {
                mBmTemp.eraseColor(Color.TRANSPARENT);
                mImgTemp.setImageBitmap(mBmTemp);
                mBm.eraseColor(Color.TRANSPARENT);
                mImg.setImageBitmap(mBmTemp);

                while (hisList.size() > 0) hisList.remove(hisList.size() - 1);

                graph_Step = 0;
                sector_Step = 0;
                pointNum = 0;
                Toast.makeText(DrawActivity.this, "新建成功", Toast.LENGTH_SHORT).show();
                mFd.closeMenu();
            }
        });

        aSbt.setOnClickListener(new View.OnClickListener() {//关于
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DrawActivity.this, AboutActivity.class);
                startActivity(intent);
                mFd.closeMenu();
            }
        });
        quitBt.setOnClickListener(new View.OnClickListener() {//退出
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        bTYes.setOnClickListener(new View.OnClickListener() {//多边形确认操作
            @Override
            public void onClick(View v) {
                bTYes.setVisibility(View.GONE);
                bTNo.setVisibility(View.GONE);
                if (isPolygonFilled) {
                    mCv.drawPath(mPath, mPt_Fill);
                }
                mCv.drawPath(mPath, mPt_Border);

                mPath.reset();
                mBmTemp.eraseColor(Color.TRANSPARENT);
                mImgTemp.setImageBitmap(mBmTemp);
                pointNum = 0;

                saveHis();
            }
        });
        bTNo.setOnClickListener(new View.OnClickListener() {//多边形取消操作
            @Override
            public void onClick(View v) {
                bTYes.setVisibility(View.GONE);
                bTNo.setVisibility(View.GONE);

                mPath.reset();
                mBmTemp.eraseColor(Color.TRANSPARENT);
                mImgTemp.setImageBitmap(mBmTemp);
                pointNum = 0;
            }
        });

        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        for (int i = 0; i < menuButton.getPiecePlaceEnum().pieceNumber(); i++) {//装载工具
            TextInsideCircleButton.Builder builder = new TextInsideCircleButton.Builder();
            builder.normalImageRes(toolId[i]);
            builder.normalText(toolName[i]);
            builder.shadowEffect(false);
            builder.buttonCornerRadius(Util.dp2px(0));
            builder.imagePadding(new Rect(20, 20, 20, 60));
            builder.textSize(12);
            builder.normalColor(R.color.colorPureBlue);
            builder.textPadding(new Rect(0, 10, 0, 0));
            builder.isRound(false);
            builder.listener(new OnBMClickListener() {
                @Override
                public void onBoomButtonClick(int index) {

                    toolNum = index;
                    switch (index) {
                        case 0: {
                            pen.setBackgroundColor(0xff5fcdff);
                            eraser.setBackgroundColor(0xff5ba4dc);
                            @SuppressLint("InflateParams") View view = getLayoutInflater().inflate(R.layout.pen_settings, null);
                            final EditText editText_Size = view.findViewById(R.id.pen_size);
                            final RadioButton sRb = view.findViewById(R.id.pen_solid);
                            final RadioButton sRb2 = view.findViewById(R.id.pen_dotted);

                            editText_Size.setHint("大小(当前为" + pen_Size + ")");
                            if (isPenIsSolid) sRb.setChecked(true);
                            else sRb2.setChecked(true);

                            AlertDialog alertDialog = new AlertDialog.Builder(DrawActivity.this)
                                    .setTitle("画笔属性")
                                    .setView(view)
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (!TextUtils.isEmpty(editText_Size.getText()))
                                                pen_Size = Integer.parseInt(editText_Size.getText().toString());

                                            isPenIsSolid = sRb.isChecked();

                                            String mS = isPenIsSolid ? "实线" : "虚线";
                                            Toast.makeText(DrawActivity.this, "大小" + pen_Size + "\n" + mS, Toast.LENGTH_SHORT).show();
                                            dialog.dismiss();
                                        }
                                    }).create();
                            alertDialog.show();

                        }
                        break;
                        case 1: {
                            eraser.setBackgroundColor(0xff5fcdff);
                            pen.setBackgroundColor(0xff5ba4dc);
                            @SuppressLint("InflateParams") View view = getLayoutInflater().inflate(R.layout.eraser_settings, null);
                            final EditText editText_Size = view.findViewById(R.id.eraser_size);

                            editText_Size.setHint("大小(当前为" + eraser_Size + ")");

                            AlertDialog alertDialog = new AlertDialog.Builder(DrawActivity.this)
                                    .setTitle("橡皮属性")
                                    .setView(view)
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (!TextUtils.isEmpty(editText_Size.getText()))
                                                eraser_Size = Integer.parseInt(editText_Size.getText().toString());

                                            Toast.makeText(DrawActivity.this, "大小" + eraser_Size, Toast.LENGTH_SHORT).show();

                                            dialog.dismiss();
                                        }
                                    })
                                    .create();
                            alertDialog.show();
                        }
                        break;
                        case 2: {
                            eraser.setBackgroundColor(0xff5ba4dc);
                            pen.setBackgroundColor(0xff5ba4dc);
                            @SuppressLint("InflateParams") View view = getLayoutInflater().inflate(R.layout.line_settings, null);
                            final EditText editText_Size = view.findViewById(R.id.line_size);
                            final RadioButton sRb = view.findViewById(R.id.s_l);
                            final RadioButton sRb2 = view.findViewById(R.id.d_l);

                            editText_Size.setHint("大小(当前为" + line_Size + ")");
                            if (isLineSolid) sRb.setChecked(true);
                            else sRb2.setChecked(true);

                            AlertDialog alertDialog = new AlertDialog.Builder(DrawActivity.this)
                                    .setTitle("直线属性")
                                    .setView(view)
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (!TextUtils.isEmpty(editText_Size.getText()))
                                                line_Size = Integer.parseInt(editText_Size.getText().toString());

                                            isLineSolid = sRb.isChecked();

                                            String mS = isLineSolid ? "实线" : "虚线";
                                            Toast.makeText(DrawActivity.this, "大小" + line_Size + "\n" + mS, Toast.LENGTH_SHORT).show();
                                            dialog.dismiss();
                                        }
                                    }).create();
                            alertDialog.show();
                        }
                        break;
                        case 3: {
                            eraser.setBackgroundColor(0xff5ba4dc);
                            pen.setBackgroundColor(0xff5ba4dc);
                            @SuppressLint("InflateParams") View view = getLayoutInflater().inflate(R.layout.graph_settings, null);
                            final EditText editText_Size = view.findViewById(R.id.graph_size);
                            final RadioButton sRb = view.findViewById(R.id.s_g);
                            final RadioButton sRb2 = view.findViewById(R.id.d_g);

                            editText_Size.setHint("大小(当前为" + graph_Size + ")");
                            if (isGraphSolid) sRb.setChecked(true);
                            else sRb2.setChecked(true);

                            AlertDialog alertDialog = new AlertDialog.Builder(DrawActivity.this)
                                    .setTitle("曲线属性")
                                    .setView(view)
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (!TextUtils.isEmpty(editText_Size.getText()))
                                                graph_Size = Integer.parseInt(editText_Size.getText().toString());

                                            isGraphSolid = sRb.isChecked();

                                            String mS = isGraphSolid ? "实线" : "虚线";
                                            Toast.makeText(DrawActivity.this, "大小" + graph_Size + "\n" + mS, Toast.LENGTH_SHORT).show();
                                            dialog.dismiss();
                                        }
                                    }).create();
                            alertDialog.show();
                        }
                        break;
                        case 4: {
                            eraser.setBackgroundColor(0xff5ba4dc);
                            pen.setBackgroundColor(0xff5ba4dc);
                            @SuppressLint("InflateParams") View view = getLayoutInflater().inflate(R.layout.rectangle_settings, null);
                            final EditText editText_Radius = view.findViewById(R.id.rectangle_radius);
                            final EditText editText_Border = view.findViewById(R.id.rectangle_border);
                            final RadioButton sRb = view.findViewById(R.id.solid_line);
                            final RadioButton sRb2 = view.findViewById(R.id.dotted_line);
                            final RadioButton fRb = view.findViewById(R.id.isfill);
                            final RadioButton fRb2 = view.findViewById(R.id.isnotfill);

                            editText_Radius.setHint("圆角大小(当前为" + rectangle_Radius + ")");
                            editText_Border.setHint("边框大小(当前为" + rectangle_BorderWidth + ")");

                            if (isRecSolid) sRb.setChecked(true);
                            else sRb2.setChecked(true);

                            if (isRecFilled) fRb.setChecked(true);
                            else fRb2.setChecked(true);

                            AlertDialog dialog = new AlertDialog.Builder(DrawActivity.this)
                                    .setTitle("矩形属性")
                                    .setView(view)
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                            if (!TextUtils.isEmpty(editText_Radius.getText()))
                                                rectangle_Radius = Integer.parseInt(editText_Radius.getText().toString());
                                            if (!TextUtils.isEmpty(editText_Border.getText()))
                                                rectangle_BorderWidth = Integer.parseInt(editText_Border.getText().toString());

                                            isRecSolid = sRb.isChecked();
                                            isRecFilled = fRb.isChecked();

                                            String mS = isRecSolid ? "实线" : "虚线";
                                            String mS2 = isRecFilled ? "填充" : "不填充";

                                            Toast.makeText(DrawActivity.this,
                                                    "边框大小 " + rectangle_BorderWidth + "\n圆角大小 " + rectangle_Radius + "\n" + mS + "\n" + mS2, Toast.LENGTH_SHORT).show();
                                            dialog.dismiss();
                                        }
                                    })
                                    .create();
                            dialog.show();
                        }
                        break;
                        case 5: {
                            eraser.setBackgroundColor(0xff5ba4dc);
                            pen.setBackgroundColor(0xff5ba4dc);
                            @SuppressLint("InflateParams") View view = getLayoutInflater().inflate(R.layout.cercle_settings, null);
                            final EditText editText_Border = view.findViewById(R.id.cercle_border);
                            final RadioButton cRb = view.findViewById(R.id.cercle);
                            final RadioButton cRb2 = view.findViewById(R.id.ellipse);
                            final RadioButton sRb = view.findViewById(R.id.c_solid_line);
                            final RadioButton sRb2 = view.findViewById(R.id.c_dotted_line);
                            final RadioButton fRb = view.findViewById(R.id.c_isfill);
                            final RadioButton fRb2 = view.findViewById(R.id.c_isnotfill);

                            editText_Border.setHint("边框大小(当前为" + cercle_BorderWidth + ")");

                            if (c_Or_e) cRb.setChecked(true);
                            else cRb2.setChecked(true);

                            if (isCercleSolid) sRb.setChecked(true);
                            else sRb2.setChecked(true);

                            if (isCercleFilled) fRb.setChecked(true);
                            else fRb2.setChecked(true);

                            AlertDialog dialog = new AlertDialog.Builder(DrawActivity.this)
                                    .setTitle("圆形属性")
                                    .setView(view)
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (!TextUtils.isEmpty(editText_Border.getText()))
                                                cercle_BorderWidth = Integer.parseInt(editText_Border.getText().toString());

                                            c_Or_e = cRb.isChecked();
                                            isCercleSolid = sRb.isChecked();
                                            isCercleFilled = fRb.isChecked();

                                            String mS0 = c_Or_e ? "正圆" : "椭圆";
                                            String mS1 = isCercleSolid ? "实线" : "虚线";
                                            String mS2 = isCercleFilled ? "填充" : "不填充";

                                            Toast.makeText(DrawActivity.this,
                                                    "边框大小 " + cercle_BorderWidth + "\n" + mS0 + "\n" + mS1 + "\n" + mS2, Toast.LENGTH_SHORT).show();
                                            dialog.dismiss();
                                        }
                                    })
                                    .create();
                            dialog.show();
                        }
                        break;
                        case 6: {
                            eraser.setBackgroundColor(0xff5ba4dc);
                            pen.setBackgroundColor(0xff5ba4dc);
                            @SuppressLint("InflateParams") View view = getLayoutInflater().inflate(R.layout.polygon_settings, null);
                            final EditText editText_Border = view.findViewById(R.id.polygon_border);
                            final RadioButton sRb = view.findViewById(R.id.p_solid_line);
                            final RadioButton sRb2 = view.findViewById(R.id.p_dotted_line);
                            final RadioButton fRb = view.findViewById(R.id.p_isfill);
                            final RadioButton fRb2 = view.findViewById(R.id.p_isnotfill);

                            editText_Border.setHint("边框大小(当前为" + polygon_Size + ")");

                            if (isPolygonSolid) sRb.setChecked(true);
                            else sRb2.setChecked(true);

                            if (isPolygonFilled) fRb.setChecked(true);
                            else fRb2.setChecked(true);

                            AlertDialog dialog = new AlertDialog.Builder(DrawActivity.this)
                                    .setTitle("多边形属性")
                                    .setView(view)
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (!TextUtils.isEmpty(editText_Border.getText()))
                                                polygon_Size = Integer.parseInt(editText_Border.getText().toString());

                                            isPolygonSolid = sRb.isChecked();
                                            isPolygonFilled = fRb.isChecked();

                                            String mS1 = isPolygonSolid ? "实线" : "虚线";
                                            String mS2 = isPolygonFilled ? "填充" : "不填充";

                                            Toast.makeText(DrawActivity.this,
                                                    "边框大小 " + polygon_Size + "\n" + mS1 + "\n" + mS2, Toast.LENGTH_SHORT).show();
                                            dialog.dismiss();
                                        }
                                    })
                                    .create();
                            dialog.show();
                        }
                        break;
                        case 7: {
                            eraser.setBackgroundColor(0xff5ba4dc);
                            pen.setBackgroundColor(0xff5ba4dc);
                            @SuppressLint("InflateParams") View view = getLayoutInflater().inflate(R.layout.text_settings, null);
                            final EditText editText_Content = view.findViewById(R.id.text_content);
                            final EditText editText_Border_Size = view.findViewById(R.id.text_b_size);
                            final EditText editText_Border = view.findViewById(R.id.text_size);
                            final RadioButton sRb = view.findViewById(R.id.t_solid_line);
                            final RadioButton sRb2 = view.findViewById(R.id.t_dotted_line);
                            final RadioButton fRb = view.findViewById(R.id.t_isfill);
                            final RadioButton fRb2 = view.findViewById(R.id.t_isnotfill);

                            editText_Border.setHint("文字大小(当前为" + text_Size + ")");
                            editText_Border_Size.setHint("描边大小(当前为" + f_B_Size + ")");

                            if (isTextSolid) sRb.setChecked(true);
                            else sRb2.setChecked(true);

                            if (isTextFilled) fRb.setChecked(true);
                            else fRb2.setChecked(true);

                            AlertDialog dialog = new AlertDialog.Builder(DrawActivity.this)
                                    .setTitle("文本属性")
                                    .setView(view)
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (!TextUtils.isEmpty(editText_Border.getText()))
                                                text_Size = Integer.parseInt(editText_Border.getText().toString());
                                            if (!TextUtils.isEmpty(editText_Content.getText()))
                                                text_Content = editText_Content.getText().toString();
                                            if (!TextUtils.isEmpty(editText_Border_Size.getText()))
                                                f_B_Size = Integer.parseInt(editText_Border_Size.getText().toString());

                                            isTextSolid = sRb.isChecked();
                                            isTextFilled = fRb.isChecked();

                                            String mS1 = isTextSolid ? "实线" : "虚线";
                                            String mS2 = isTextFilled ? "填充" : "不填充";

                                            Toast.makeText(DrawActivity.this,
                                                    "字体大小 " + cercle_BorderWidth + "\n" + "描边大小" + f_B_Size + "\n" + mS1 + "\n" + mS2, Toast.LENGTH_SHORT).show();
                                            dialog.dismiss();
                                        }
                                    })
                                    .create();
                            dialog.show();
                        }
                        break;
                        case 8: {
                            eraser.setBackgroundColor(0xff5ba4dc);
                            pen.setBackgroundColor(0xff5ba4dc);
                            @SuppressLint("InflateParams") View view = getLayoutInflater().inflate(R.layout.cercle_settings, null);
                            final EditText editText_Border = view.findViewById(R.id.cercle_border);
                            final RadioButton cRb = view.findViewById(R.id.cercle);
                            final RadioButton cRb2 = view.findViewById(R.id.ellipse);
                            final RadioButton sRb = view.findViewById(R.id.c_solid_line);
                            final RadioButton sRb2 = view.findViewById(R.id.c_dotted_line);
                            final RadioButton fRb = view.findViewById(R.id.c_isfill);
                            final RadioButton fRb2 = view.findViewById(R.id.c_isnotfill);
                            final TextView textView = view.findViewById(R.id.is_close);

                            textView.setText("是否闭合");
                            cRb.setText("是");
                            cRb2.setText("否");

                            editText_Border.setHint("边框大小(当前为" + sector_BorderWidth + ")");

                            if (isSectorClose) cRb.setChecked(true);
                            else cRb2.setChecked(true);

                            if (isSectorSolid) sRb.setChecked(true);
                            else sRb2.setChecked(true);

                            if (isSectorFilled) fRb.setChecked(true);
                            else fRb2.setChecked(true);

                            AlertDialog dialog = new AlertDialog.Builder(DrawActivity.this)
                                    .setTitle("扇形属性")
                                    .setView(view)
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    })
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (!TextUtils.isEmpty(editText_Border.getText()))
                                                sector_BorderWidth = Integer.parseInt(editText_Border.getText().toString());

                                            isSectorClose = cRb.isChecked();
                                            isSectorSolid = sRb.isChecked();
                                            isSectorFilled = fRb.isChecked();

                                            String mS0 = isSectorClose ? "闭合" : "不闭合";
                                            String mS1 = isSectorSolid ? "实线" : "虚线";
                                            String mS2 = isSectorFilled ? "填充" : "不填充";

                                            Toast.makeText(DrawActivity.this,
                                                    "边框大小 " + sector_BorderWidth + "\n" + mS0 + "\n" + mS1 + "\n" + mS2, Toast.LENGTH_SHORT).show();
                                            dialog.dismiss();
                                        }
                                    })
                                    .create();
                            dialog.show();
                        }
                        break;
                    }
                    Toast.makeText(DrawActivity.this, toolName[index], Toast.LENGTH_SHORT).show();
                }
            });
            menuButton.addBuilder(builder);
        }

        ////////////////////颜色工具栏
        RapidFloatingActionContentLabelList rfaContent = new RapidFloatingActionContentLabelList(this);
        rfaContent.setOnRapidFloatingActionContentLabelListListener(this);
        List<RFACLabelItem> items = new ArrayList<>();
        items.add(new RFACLabelItem<Integer>()
                .setIconNormalColor(Color.WHITE)
                .setIconPressedColor(Color.WHITE)
                .setWrapper(0)
                .setResId(R.drawable.transparent)
                .setLabel("白色")
        );
        items.add(new RFACLabelItem<Integer>()
                .setIconNormalColor(Color.GRAY)
                .setIconPressedColor(Color.GRAY)
                .setWrapper(0)
                .setResId(R.drawable.transparent)
                .setLabel("灰色")
        );
        items.add(new RFACLabelItem<Integer>()
                .setIconNormalColor(Color.BLACK)
                .setIconPressedColor(Color.BLACK)
                .setWrapper(0)
                .setResId(R.drawable.transparent)
                .setLabel("黑色")
        );
        items.add(new RFACLabelItem<Integer>()
                .setIconNormalColor(Color.RED)
                .setIconPressedColor(Color.RED)
                .setWrapper(0)
                .setResId(R.drawable.transparent)
                .setLabel("红色")
        );
        items.add(new RFACLabelItem<Integer>()
                .setIconNormalColor(Color.YELLOW)
                .setIconPressedColor(Color.YELLOW)
                .setWrapper(0)
                .setResId(R.drawable.transparent)
                .setLabel("黄色")
        );
        items.add(new RFACLabelItem<Integer>()
                .setIconNormalColor(Color.GREEN)
                .setIconPressedColor(Color.GREEN)
                .setWrapper(0)
                .setResId(R.drawable.transparent)
                .setLabel("绿色")
        );
        items.add(new RFACLabelItem<Integer>()
                .setIconNormalColor(borderColor)
                .setIconPressedColor(borderColor)
                .setWrapper(0)
                .setResId(R.drawable.color_chooser_b)
                .setLabel("笔触颜色")
        );
        items.add(new RFACLabelItem<Integer>()
                .setIconNormalColor(fillColor)
                .setIconPressedColor(fillColor)
                .setWrapper(0)
                .setResId(R.drawable.color_chooser)
                .setLabel("填充颜色")
        );
        rfaContent
                .setItems(items)
                .setIconShadowColor(0xff888888)
        ;
        rHep = new RapidFloatingActionHelper(this, rFal, rFbt, rfaContent).build();

        drawImage();

        mImg.startAnimation(a3);
        mImgTemp.startAnimation(a3);
        textView_Title.startAnimation(a1);
        mSbt.startAnimation(a1);
        aSbt.startAnimation(a1);
        menuButton.startAnimation(a4);
        rFbt.startAnimation(a5);
        cBg.startAnimation(a5);
        re_Tool.startAnimation(a2);
    }

    @Override
    public void onRFACItemLabelClick(int position, final RFACLabelItem item) {
    }

    @Override
    public void onRFACItemIconClick(int position, final RFACLabelItem item) {
        if (position < 6) {
            if (f_Or_B) {
                fillColor = item.getIconNormalColor();
                linearGradient2 = new LinearGradient(0, 0, width, height, fillColor, fillColor, Shader.TileMode.CLAMP);
                Toast.makeText(DrawActivity.this, "填充色加载中……", Toast.LENGTH_SHORT).show();
            } else {
                borderColor = item.getIconNormalColor();
                linearGradient1 = new LinearGradient(0, 0, width, height, borderColor, borderColor, Shader.TileMode.CLAMP);
                Toast.makeText(DrawActivity.this, "边框色加载中……", Toast.LENGTH_SHORT).show();
            }
        }
        switch (position) {
            case 6: {
                f_Or_B = false;
                @SuppressLint("InflateParams") View view = getLayoutInflater().inflate(R.layout.color_settings, null);
                final ColorPicker colorPicker1 = view.findViewById(R.id.s_pick_color);
                final ColorPicker colorPicker2 = view.findViewById(R.id.g_pick_color);
                final OpacityBar opacityBar1 = view.findViewById(R.id.fill_alpha);
                final OpacityBar opacityBar2 = view.findViewById(R.id.border_alpha);
                final SVBar svBar1 = view.findViewById(R.id.fill_sv);
                final SVBar svBar2 = view.findViewById(R.id.border_sv);
                final RadioGroup radioGroup = view.findViewById(R.id.color_group);
                final RadioButton sRb = view.findViewById(R.id.simple_color);
                final RadioButton sRb2 = view.findViewById(R.id.gradients_color);
                final LinearLayout linearLayout2 = view.findViewById(R.id.right_c);

                colorPicker1.addOpacityBar(opacityBar1);
                colorPicker1.addSVBar(svBar1);
                colorPicker2.addOpacityBar(opacityBar2);
                colorPicker2.addSVBar(svBar2);

                colorPicker1.setColor(borderColor);
                colorPicker1.setNewCenterColor(borderColor);
                colorPicker1.setOldCenterColor(borderColor);
                colorPicker2.setColor(borderColor2);
                colorPicker2.setNewCenterColor(borderColor2);
                colorPicker2.setOldCenterColor(borderColor2);

                if (!borderGOrS) {
                    linearLayout2.setVisibility(View.GONE);
                    sRb.setChecked(true);
                } else {
                    sRb2.setChecked(true);
                }


                radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        switch (checkedId) {
                            case R.id.simple_color: {
                                borderGOrS = false;
                                linearLayout2.setVisibility(View.GONE);
                            }
                            break;
                            case R.id.gradients_color: {
                                linearLayout2.setVisibility(View.VISIBLE);
                                borderGOrS = true;
                            }
                            break;
                        }
                    }
                });

                AlertDialog dialog = new AlertDialog.Builder(DrawActivity.this)
                        .setTitle("笔触颜色")
                        .setView(view)
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (borderGOrS) {
                                    borderColor = colorPicker1.getColor();
                                    borderColor2 = colorPicker2.getColor();
                                    linearGradient1 = new LinearGradient(0, 0, width, height, borderColor, borderColor2, Shader.TileMode.CLAMP);
                                } else {
                                    borderColor = colorPicker1.getColor();
                                    linearGradient1 = new LinearGradient(0, 0, width, height, borderColor, borderColor, Shader.TileMode.CLAMP);
                                }

                                dialog.dismiss();
                            }
                        })
                        .create();
                dialog.show();
            }
            break;
            case 7: {
                f_Or_B = true;
                @SuppressLint("InflateParams") View view = getLayoutInflater().inflate(R.layout.color_settings, null);
                final ColorPicker colorPicker1 = view.findViewById(R.id.s_pick_color);
                final ColorPicker colorPicker2 = view.findViewById(R.id.g_pick_color);
                final OpacityBar opacityBar1 = view.findViewById(R.id.fill_alpha);
                final OpacityBar opacityBar2 = view.findViewById(R.id.border_alpha);
                final SVBar svBar1 = view.findViewById(R.id.fill_sv);
                final SVBar svBar2 = view.findViewById(R.id.border_sv);
                final RadioGroup radioGroup = view.findViewById(R.id.color_group);
                final RadioButton sRb = view.findViewById(R.id.simple_color);
                final RadioButton sRb2 = view.findViewById(R.id.gradients_color);
                final LinearLayout linearLayout2 = view.findViewById(R.id.right_c);

                colorPicker1.addOpacityBar(opacityBar1);
                colorPicker1.addSVBar(svBar1);
                colorPicker2.addOpacityBar(opacityBar2);
                colorPicker2.addSVBar(svBar2);

                colorPicker1.setColor(fillColor);
                colorPicker1.setNewCenterColor(fillColor);
                colorPicker1.setOldCenterColor(fillColor);
                colorPicker2.setColor(fillColor);
                colorPicker2.setNewCenterColor(fillColor);
                colorPicker2.setOldCenterColor(fillColor);

                if (!fillGOrS) {
                    linearLayout2.setVisibility(View.GONE);
                    sRb.setChecked(true);
                } else {
                    sRb2.setChecked(true);
                }

                radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        switch (checkedId) {
                            case R.id.simple_color: {
                                fillGOrS = false;
                                linearLayout2.setVisibility(View.GONE);
                            }
                            break;
                            case R.id.gradients_color: {
                                fillGOrS = true;
                                linearLayout2.setVisibility(View.VISIBLE);
                            }
                            break;
                        }
                    }
                });

                AlertDialog dialog = new AlertDialog.Builder(DrawActivity.this)
                        .setTitle("填充颜色")
                        .setView(view)
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                fillColor = colorPicker1.getColor();
                                if (fillGOrS) {
                                    fillColor2 = colorPicker2.getColor();
                                    linearGradient2 = new LinearGradient(0, 0, width, height, fillColor, fillColor2, Shader.TileMode.CLAMP);
                                } else
                                    linearGradient2 = new LinearGradient(0, 0, width, height, fillColor, fillColor, Shader.TileMode.CLAMP);

                                dialog.dismiss();
                            }
                        })
                        .create();
                dialog.show();
            }
            break;
        }

        rHep.toggleContent();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void drawImage() {

        mImg.setMaxWidth(width);
        mImg.setMaxHeight(height);
        mImgTemp.setMaxWidth(width);
        mImgTemp.setMaxHeight(height);
        mBm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        mBmTemp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        mPt_Fill = new Paint();
        mPt_Fill.setStrokeWidth(5);
        mPt_Fill.setAntiAlias(true);
        mPt_Fill.setDither(true);
        mPt_Fill.setStyle(Paint.Style.STROKE);
        mPt_Fill.setStrokeJoin(Paint.Join.ROUND);
        mPt_Fill.setStrokeCap(Paint.Cap.ROUND);
        mPt_Fill.setStyle(Paint.Style.FILL);
        mPt_Border = new Paint();
        mPt_Border.setStrokeWidth(5);
        mPt_Border.setAntiAlias(true);
        mPt_Border.setDither(true);
        mPt_Border.setStyle(Paint.Style.STROKE);
        mPt_Border.setStrokeJoin(Paint.Join.ROUND);
        mPt_Border.setStrokeCap(Paint.Cap.ROUND);
        mPt_Border.setStyle(Paint.Style.STROKE);
        mPt_Fill.setShader(linearGradient2);
        mPt_Border.setShader(linearGradient1);
        mCv = new Canvas();
        mCvTemp = new Canvas();
        mCv.setBitmap(mBm);
        mCvTemp.setBitmap(mBmTemp);
        mCv.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
        mCvTemp.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
        mImg.setImageBitmap(mBm);
        mImgTemp.setImageBitmap(mBmTemp);
        saveHis();
        saveHis();

        openBt.setOnClickListener(new View.OnClickListener() {//打开本地文件
            @Override
            public void onClick(View v) {
                prepareToOpenAlbum();
                mFd.closeMenu();
            }
        });

        saveBt.setOnClickListener(new View.OnClickListener() {//保存到本地
            @Override
            public void onClick(View v) {
                if (isSaved) {
                    Toast.makeText(DrawActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                } else {
                    saveImageToGallery(DrawActivity.this, mBm);
                    Toast.makeText(DrawActivity.this, "图片已保存到Sdcard\\SimplePainter", Toast.LENGTH_SHORT).show();
                    mFd.closeMenu();
                    isSaved = true;
                }

            }
        });


        mImg.setOnTouchListener(new View.OnTouchListener() {
            int startX, startY;

            @Override
            public boolean onTouch(View v, final MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        startX = (int) event.getX();
                        startY = (int) event.getY();

                        mPt_Fill.setShader(linearGradient2);
                        mPt_Border.setShader(linearGradient1);

                        switch (toolNum) {
                            case 0: {
                                mPt_Border.setStrokeWidth(pen_Size);
                                mPt_Border.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
                                if (isPenIsSolid)
                                    mPt_Border.setPathEffect(null);
                                else
                                    mPt_Border.setPathEffect(new DashPathEffect(new float[]{pen_Size + pen_Size / 4 + 5, pen_Size + pen_Size / 4 + 5}, 0));
                                mCv.drawPoint(startX, startY, mPt_Border);
                                if (mPath == null) {
                                    mPath = new Path();
                                }
                                mPath.moveTo(startX, startY);
                            }
                            break;
                            case 1: {
                                mPt_Border.setPathEffect(null);
                                mPt_Border.setStrokeWidth(eraser_Size);
                                mPt_Border.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
                                mCv.drawPoint(startX, startY, mPt_Border);
                                if (mPath == null) {
                                    mPath = new Path();
                                }
                                mPath.moveTo(startX, startY);
                            }
                            break;
                            case 2: {
                                mPt_Border.setStrokeWidth(line_Size);
                                if (isLineSolid)
                                    mPt_Border.setPathEffect(null);
                                else
                                    mPt_Border.setPathEffect(new DashPathEffect(new float[]{line_Size + line_Size / 4 + 5, line_Size + line_Size / 4 + 5}, 0));
                            }
                            break;
                            case 3: {
                                mPt_Border.setStrokeWidth(graph_Size);
                                if (isGraphSolid)
                                    mPt_Border.setPathEffect(null);
                                else
                                    mPt_Border.setPathEffect(new DashPathEffect(new float[]{graph_Size + graph_Size / 4 + 5, graph_Size + graph_Size / 4 + 5}, 0));
                                if (mPath == null) {
                                    mPath = new Path();
                                }
                                if (graph_Step == 0) {
                                    gSX = startX;
                                    gSY = startY;
                                    mPath.moveTo(gSX, gSY);
                                }

                            }
                            break;
                            case 4: {
                                mPt_Border.setStrokeWidth(rectangle_BorderWidth);
                                if (isRecSolid)
                                    mPt_Border.setPathEffect(null);
                                else
                                    mPt_Border.setPathEffect(new DashPathEffect(new float[]{rectangle_BorderWidth + rectangle_BorderWidth / 4 + 5, rectangle_BorderWidth + rectangle_BorderWidth / 4 + 5}, 0));
                            }
                            break;
                            case 5: {
                                mPt_Border.setStrokeWidth(cercle_BorderWidth);
                                if (isCercleSolid)
                                    mPt_Border.setPathEffect(null);
                                else
                                    mPt_Border.setPathEffect(new DashPathEffect(new float[]{cercle_BorderWidth + cercle_BorderWidth / 4 + 5, cercle_BorderWidth + cercle_BorderWidth / 4 + 5}, 0));
                            }
                            break;
                            case 6: {
                                bTYes.setVisibility(View.VISIBLE);
                                bTNo.setVisibility(View.VISIBLE);

                                mPt_Border.setStrokeWidth(polygon_Size);
                                if (isPolygonSolid)
                                    mPt_Border.setPathEffect(null);
                                else
                                    mPt_Border.setPathEffect(new DashPathEffect(new float[]{polygon_Size + polygon_Size / 4 + 5, polygon_Size + polygon_Size / 4 + 5}, 0));
                                if (mPath == null) {
                                    mPath = new Path();
                                }

                                if (pointNum == 0)
                                    polPoint[pointNum] = new Point(startX, startY);
                                mPath.moveTo(polPoint[pointNum].x, polPoint[pointNum].y);
                                pointNum++;
                            }
                            break;
                            case 7: {
                                mPt_Border.setStrokeWidth(f_B_Size);
                                if (isTextSolid)
                                    mPt_Border.setPathEffect(null);
                                else
                                    mPt_Border.setPathEffect(new DashPathEffect(new float[]{f_B_Size + f_B_Size / 4 + 5, f_B_Size + f_B_Size / 4 + 5}, 0));
                            }
                            break;
                            case 8: {
                                mPt_Border.setStrokeWidth(sector_BorderWidth);
                                if (isSectorSolid)
                                    mPt_Border.setPathEffect(null);
                                else
                                    mPt_Border.setPathEffect(new DashPathEffect(new float[]{sector_BorderWidth + sector_BorderWidth / 4 + 5, sector_BorderWidth + sector_BorderWidth / 4 + 5}, 0));
                            }
                            break;
                        }
                    }
                    break;

                    case MotionEvent.ACTION_MOVE: {
                        final int endX = (int) event.getX();
                        final int endY = (int) event.getY();
                        switch (toolNum) {
                            case 0: {//画笔使用填充色
                                mPath.quadTo(startX, startY, (startX + endX) / 2, (startY + endY) / 2);
                                mCv.drawPath(mPath, mPt_Border);
                                startX = (int) event.getX();
                                startY = (int) event.getY();
                                mImg.setImageBitmap(mBm);
                            }
                            break;
                            case 1: {//橡皮
                                mPath.quadTo(startX, startY, (startX + endX) / 2, (startY + endY) / 2);
                                mCv.drawPath(mPath, mPt_Border);
                                startX = (int) event.getX();
                                startY = (int) event.getY();
                                mImg.setImageBitmap(mBm);
                            }
                            break;
                            case 2: {//直线
                                mBmTemp.eraseColor(Color.TRANSPARENT);
                                mImgTemp.setImageBitmap(mBmTemp);
                                mCvTemp.drawLine(startX, startY, endX, endY, mPt_Border);
                                mImgTemp.setImageBitmap(mBmTemp);
                            }
                            break;
                            case 3: {//曲线
                                mBmTemp.eraseColor(Color.TRANSPARENT);
                                mImgTemp.setImageBitmap(mBmTemp);
                                mPath.reset();
                                mPath.moveTo(gSX, gSY);
                                switch (graph_Step) {
                                    case 0: {
                                        mPath.lineTo(endX, endY);
                                        mCvTemp.drawPath(mPath, mPt_Border);
                                        gEX = endX;
                                        gEY = endY;
                                    }
                                    break;
                                    case 1: {
                                        cDX1 = (int) event.getX();
                                        cDY1 = (int) event.getY();
                                        cDX2 = (int) event.getX();
                                        cDY2 = (int) event.getY();
                                        mPath.cubicTo(cDX1, cDY1, cDX2, cDY2, gEX, gEY);
                                        mCvTemp.drawPath(mPath, mPt_Border);
                                    }
                                    break;
                                    case 2: {
                                        cDX2 = (int) event.getX();
                                        cDY2 = (int) event.getY();
                                        mPath.cubicTo(cDX1, cDY1, cDX2, cDY2, gEX, gEY);
                                        mCvTemp.drawPath(mPath, mPt_Border);
                                    }
                                    break;
                                }
                            }
                            break;
                            case 4: {//矩形混合使用
                                mBmTemp.eraseColor(Color.TRANSPARENT);
                                mImgTemp.setImageBitmap(mBmTemp);
                                if (isRecFilled)
                                    mCvTemp.drawRoundRect(new RectF(startX, startY, endX, endY), rectangle_Radius * 5, rectangle_Radius * 5, mPt_Fill);
                                mCvTemp.drawRoundRect(new RectF(startX, startY, endX, endY), rectangle_Radius * 5, rectangle_Radius * 5, mPt_Border);
                                mImgTemp.setImageBitmap(mBmTemp);

                            }
                            break;
                            case 5: {//圆形混合使用
                                mBmTemp.eraseColor(Color.TRANSPARENT);
                                mImgTemp.setImageBitmap(mBmTemp);
                                int r = (int) Math.sqrt(Math.pow(startX - endX, 2) + Math.pow(startY - endY, 2));
                                if (c_Or_e) {
                                    if (isCercleFilled) {
                                        mCvTemp.drawCircle(startX, startY, r, mPt_Fill);
                                    }
                                    mCvTemp.drawCircle(startX, startY, r, mPt_Border);
                                } else {
                                    if (isCercleFilled) {
                                        mCvTemp.drawOval(new RectF(startX, startY, endX, endY), mPt_Fill);
                                    }
                                    mCvTemp.drawOval(new RectF(startX, startY, endX, endY), mPt_Border);
                                }
                                mImgTemp.setImageBitmap(mBmTemp);
                            }
                            break;
                            case 6: {//多边形混合使用
                                mPath.reset();
                                mBmTemp.eraseColor(Color.TRANSPARENT);
                                mImgTemp.setImageBitmap(mBmTemp);
                                mPath.moveTo(polPoint[0].x, polPoint[0].y);
                                for (int t = 0; t < pointNum; t++) {
                                    mPath.lineTo(polPoint[t].x, polPoint[t].y);
                                }
                                mPath.lineTo(endX, endY);
                                mPath.lineTo(polPoint[0].x, polPoint[0].y);
                                mPath.close();
                                if (isPolygonFilled) {
                                    mCvTemp.drawPath(mPath, mPt_Fill);
                                }
                                mCvTemp.drawPath(mPath, mPt_Border);
                                mImgTemp.setImageBitmap(mBmTemp);
                            }
                            break;
                            case 7: {//文本
                                mBmTemp.eraseColor(Color.TRANSPARENT);
                                mImgTemp.setImageBitmap(mBmTemp);
                                if ((endX - startX) / text_Content.length() < text_Size) {
                                    mPt_Border.setTextSize((endX - startX) / text_Content.length());
                                    mPt_Fill.setTextSize((endX - startX) / text_Content.length());
                                } else {
                                    mPt_Border.setTextSize(text_Size);
                                    mPt_Fill.setTextSize(text_Size);
                                }
                                if (isTextFilled) {
                                    mCvTemp.drawText(text_Content, startX, startY, mPt_Fill);
                                }
                                mCvTemp.drawText(text_Content, startX, startY, mPt_Border);
                                mImgTemp.setImageBitmap(mBmTemp);
                            }
                            break;
                            case 8: {//扇形混合使用
                                mBmTemp.eraseColor(Color.TRANSPARENT);
                                mImgTemp.setImageBitmap(mBmTemp);
                                switch (sector_Step) {
                                    case 0: {
                                        if (isSectorFilled) {
                                            if (endX > startX && endY > startY)
                                                mCvTemp.drawArc(new RectF(startX, startY, endX, endY), 0, 360, isSectorClose, mPt_Fill);
                                            else if (endX < startX && endY < startY)
                                                mCvTemp.drawArc(new RectF(endX, endY, startX, startY), 0, 360, isSectorClose, mPt_Fill);
                                            else if (endX < startX && endY > startY)
                                                mCvTemp.drawArc(new RectF(endX, startY, startX, endY), 0, 360, isSectorClose, mPt_Fill);
                                            else
                                                mCvTemp.drawArc(new RectF(startX, endY, endX, startY), 0, 360, isSectorClose, mPt_Fill);
                                        }
                                        if (endX > startX && endY > startY)
                                            mCvTemp.drawArc(new RectF(startX, startY, endX, endY), 0, 360, isSectorClose, mPt_Border);
                                        else if (endX < startX && endY < startY)
                                            mCvTemp.drawArc(new RectF(endX, endY, startX, startY), 0, 360, isSectorClose, mPt_Border);
                                        else if (endX < startX && endY > startY)
                                            mCvTemp.drawArc(new RectF(endX, startY, startX, endY), 0, 360, isSectorClose, mPt_Border);
                                        else
                                            mCvTemp.drawArc(new RectF(startX, endY, endX, startY), 0, 360, isSectorClose, mPt_Border);
                                    }
                                    break;
                                    case 1: {
                                        sAngle = (Math.atan2(endY - centerY, endX - centerX) * (180 / Math.PI));
                                        if (isSectorFilled) {
                                            if (eX > sX && eY > sY)
                                                mCvTemp.drawArc(new RectF(sX, sY, eX, eY), (float) sAngle, 360, isSectorClose, mPt_Fill);
                                            else if (eX < sX && eY < sY)
                                                mCvTemp.drawArc(new RectF(eX, eY, sX, sY), (float) sAngle, 360, isSectorClose, mPt_Fill);
                                            else if (eX < sX && eY > sY)
                                                mCvTemp.drawArc(new RectF(eX, sY, sX, eY), (float) sAngle, 360, isSectorClose, mPt_Fill);
                                            else
                                                mCvTemp.drawArc(new RectF(sX, eY, eX, sY), (float) sAngle, 360, isSectorClose, mPt_Fill);
                                        }
                                        if (eX > sX && eY > sY)
                                            mCvTemp.drawArc(new RectF(sX, sY, eX, eY), (float) sAngle, 360, isSectorClose, mPt_Border);
                                        else if (eX < sX && eY < sY)
                                            mCvTemp.drawArc(new RectF(eX, eY, sX, sY), (float) sAngle, 360, isSectorClose, mPt_Border);
                                        else if (eX < sX && eY > sY)
                                            mCvTemp.drawArc(new RectF(eX, sY, sX, eY), (float) sAngle, 360, isSectorClose, mPt_Border);
                                        else
                                            mCvTemp.drawArc(new RectF(sX, eY, eX, sY), (float) sAngle, 360, isSectorClose, mPt_Border);
                                    }
                                    break;
                                    case 2: {
                                        eAngle = (Math.atan2(endY - centerY, endX - centerX) * (180 / Math.PI));
                                        if (isSectorFilled) {
                                            if (sAngle <= eAngle && eAngle <= 180) {
                                                dAngel = eAngle - sAngle;
                                                if (eX > sX && eY > sY)
                                                    mCvTemp.drawArc(new RectF(sX, sY, eX, eY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Fill);
                                                else if (eX < sX && eY < sY)
                                                    mCvTemp.drawArc(new RectF(eX, eY, sX, sY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Fill);
                                                else if (eX < sX && eY > sY)
                                                    mCvTemp.drawArc(new RectF(eX, sY, sX, eY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Fill);
                                                else
                                                    mCvTemp.drawArc(new RectF(sX, eY, eX, sY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Fill);
                                            } else {
                                                dAngel = 360 - sAngle + eAngle;
                                                if (eX > sX && eY > sY)
                                                    mCvTemp.drawArc(new RectF(sX, sY, eX, eY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Fill);
                                                else if (eX < sX && eY < sY)
                                                    mCvTemp.drawArc(new RectF(eX, eY, sX, sY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Fill);
                                                else if (eX < sX && eY > sY)
                                                    mCvTemp.drawArc(new RectF(eX, sY, sX, eY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Fill);
                                                else
                                                    mCvTemp.drawArc(new RectF(sX, eY, eX, sY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Fill);
                                            }
                                        }
                                        if (sAngle <= eAngle && eAngle <= 180) {
                                            dAngel = eAngle - sAngle;
                                            if (eX > sX && eY > sY)
                                                mCvTemp.drawArc(new RectF(sX, sY, eX, eY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Border);
                                            else if (eX < sX && eY < sY)
                                                mCvTemp.drawArc(new RectF(eX, eY, sX, sY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Border);
                                            else if (eX < sX && eY > sY)
                                                mCvTemp.drawArc(new RectF(eX, sY, sX, eY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Border);
                                            else
                                                mCvTemp.drawArc(new RectF(sX, eY, eX, sY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Border);
                                        } else {
                                            dAngel = 360 - sAngle + eAngle;
                                            if (eX > sX && eY > sY)
                                                mCvTemp.drawArc(new RectF(sX, sY, eX, eY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Border);
                                            else if (eX < sX && eY < sY)
                                                mCvTemp.drawArc(new RectF(eX, eY, sX, sY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Border);
                                            else if (eX < sX && eY > sY)
                                                mCvTemp.drawArc(new RectF(eX, sY, sX, eY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Border);
                                            else
                                                mCvTemp.drawArc(new RectF(sX, eY, eX, sY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Border);
                                        }
                                    }
                                    break;
                                }

                                mImgTemp.setImageBitmap(mBmTemp);

                            }
                            break;
                        }
                    }
                    break;

                    case MotionEvent.ACTION_UP: {
                        int endX = (int) event.getX();
                        int endY = (int) event.getY();
                        switch (toolNum) {
                            case 0: {
                                mPath.reset();
                                saveHis();
                            }
                            break;
                            case 1: {
                                mPt_Border.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
                                mPath.reset();
                                saveHis();
                            }
                            break;
                            case 2: {
                                mCv.drawLine(startX, startY, endX, endY, mPt_Border);
                                mImg.setImageBitmap(mBm);
                                mBmTemp.eraseColor(Color.TRANSPARENT);
                                mImgTemp.setImageBitmap(mBmTemp);
                                saveHis();
                            }
                            break;
                            case 3: {
                                switch (graph_Step) {
                                    case 0: {
                                        graph_Step++;
                                    }
                                    break;
                                    case 1: {
                                        graph_Step++;
                                    }
                                    break;
                                    case 2: {
                                        mCv.drawPath(mPath, mPt_Border);
                                        graph_Step = 0;
                                        mBmTemp.eraseColor(Color.TRANSPARENT);
                                        mImgTemp.setImageBitmap(mBmTemp);
                                        mPath.reset();
                                        saveHis();
                                    }
                                    break;
                                }
                            }
                            break;
                            case 4: {
                                if (isRecFilled)
                                    mCv.drawRoundRect(new RectF(startX, startY, endX, endY), rectangle_Radius * 5, rectangle_Radius * 5, mPt_Fill);
                                mCv.drawRoundRect(new RectF(startX, startY, endX, endY), rectangle_Radius * 5, rectangle_Radius * 5, mPt_Border);
                                mImg.setImageBitmap(mBm);
                                mBmTemp.eraseColor(Color.TRANSPARENT);
                                mImgTemp.setImageBitmap(mBmTemp);
                                saveHis();
                            }
                            break;
                            case 5: {
                                int r = (int) Math.sqrt(Math.pow(startX - endX, 2) + Math.pow(startY - endY, 2));
                                if (c_Or_e) {
                                    if (isCercleFilled) {
                                        mCv.drawCircle(startX, startY, r, mPt_Fill);
                                    }
                                    mCv.drawCircle(startX, startY, r, mPt_Border);
                                } else {
                                    if (isCercleFilled) {
                                        mCv.drawOval(new RectF(startX, startY, endX, endY), mPt_Fill);
                                    }
                                    mCv.drawOval(new RectF(startX, startY, endX, endY), mPt_Border);
                                }
                                mImg.setImageBitmap(mBm);
                                mBmTemp.eraseColor(Color.TRANSPARENT);
                                mImgTemp.setImageBitmap(mBmTemp);
                                saveHis();
                            }
                            break;
                            case 6: {
                                polPoint[pointNum] = new Point();
                                polPoint[pointNum].x = endX;
                                polPoint[pointNum].y = endY;
                            }
                            break;
                            case 7: {
                                if (isTextFilled) {
                                    mCv.drawText(text_Content, startX, startY, mPt_Fill);
                                }
                                mCv.drawText(text_Content, startX, startY, mPt_Border);
                                mImg.setImageBitmap(mBm);
                                mBmTemp.eraseColor(Color.TRANSPARENT);
                                mImgTemp.setImageBitmap(mBmTemp);
                                saveHis();
                            }
                            break;
                            case 8: {
                                if (sector_Step == 0) {
                                    sX = startX;
                                    sY = startY;
                                    eX = endX;
                                    eY = endY;
                                    centerX = (endX - startX) / 2 + sX;
                                    centerY = (endY - startY) / 2 + sY;
                                    sector_Step++;
                                } else if (sector_Step == 1) {
                                    sector_Step++;
                                } else if (sector_Step == 2) {
                                    if (isSectorFilled) {
                                        if (eX > sX && eY > sY)
                                            mCv.drawArc(new RectF(sX, sY, eX, eY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Fill);
                                        else if (eX < sX && eY < sY)
                                            mCv.drawArc(new RectF(eX, eY, sX, sY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Fill);
                                        else if (eX < sX && eY > sY)
                                            mCv.drawArc(new RectF(eX, sY, sX, eY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Fill);
                                        else
                                            mCv.drawArc(new RectF(sX, eY, eX, sY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Fill);
                                    }
                                    if (eX > sX && eY > sY)
                                        mCv.drawArc(new RectF(sX, sY, eX, eY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Border);
                                    else if (eX < sX && eY < sY)
                                        mCv.drawArc(new RectF(eX, eY, sX, sY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Border);
                                    else if (eX < sX && eY > sY)
                                        mCv.drawArc(new RectF(eX, sY, sX, eY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Border);
                                    else
                                        mCv.drawArc(new RectF(sX, eY, eX, sY), (float) sAngle, (float) dAngel, isSectorClose, mPt_Border);
                                    sector_Step = 0;

                                    mBmTemp.eraseColor(Color.TRANSPARENT);
                                    mImgTemp.setImageBitmap(mBmTemp);
                                    saveHis();
                                }
                            }
                            break;
                        }
                    }
                    break;
                }
                return true;
            }
        });

        pen.setOnTouchListener(new View.OnTouchListener() {//快速选择画笔
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    toolNum = 0;
                    pen.setBackgroundColor(0xff5fcdff);
                    eraser.setBackgroundColor(0xff5ba4dc);
                }
                return true;
            }
        });
        eraser.setOnTouchListener(new View.OnTouchListener() {//快速选择橡皮
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    toolNum = 1;
                    eraser.setBackgroundColor(0xff5fcdff);
                    pen.setBackgroundColor(0xff5ba4dc);
                }
                return true;
            }
        });
        revoke.setOnTouchListener(new View.OnTouchListener() {//撤销
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        revoke.setBackgroundColor(0xff5fcdff);
                        if (hisList.size() > 1) revokeHis();
                    }
                    break;
                    case MotionEvent.ACTION_UP: {
                        revoke.setBackgroundColor(0xff5ba4dc);
                    }
                    break;
                }
                return true;
            }
        });
        clean.setOnTouchListener(new View.OnTouchListener() {//清空画布
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        clean.setBackgroundColor(0xff5fcdff);
                        cleanDraw();
                    }
                    break;
                    case MotionEvent.ACTION_UP: {
                        clean.setBackgroundColor(0xff5ba4dc);
                    }
                    break;
                }
                return true;
            }
        });
    }

    public void saveHis() {//保存画布
        Bitmap tBm;
        //noinspection UnusedAssignment
        tBm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        tBm = mBm.copy(Bitmap.Config.ARGB_8888, true);
        if (hisList.size() >= 20) {
            hisList.remove(0);
        }
        hisList.add(tBm);
        isSaved = false;
    }

    public void revokeHis() {//撤销操作
        mBm = (Bitmap) hisList.get(hisList.size() - 2);
        mCv.setBitmap(mBm);
        mImg.setImageBitmap(mBm);
        hisList.remove(hisList.size() - 1);
        if (hisList.size() == 1) {
            mBm.eraseColor(Color.WHITE);
            saveHis();
        }
    }

    public void cleanDraw() {//清空画布
        mBm.eraseColor(Color.WHITE);
        mImg.setImageBitmap(mBm);
        saveHis();
    }

    //////////////////////////////////////////////////别人的方法///////////////////////////////////////////////////////////////////////////////
    //点击两次退出
    @Override
    public void onBackPressed() {
        long currentTime = System.currentTimeMillis();
        if ((currentTime - startTime) >= 2000) {
            Toast.makeText(DrawActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
            startTime = currentTime;
        } else {
            finish();
        }
    }

    //图片导入
    private void prepareToOpenAlbum() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_PERMISSION_GRANT);
        } else {
            openAlbum();
        }
    }

    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_CHOOSE_IMAGE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_WRITE_EXTERNAL_PERMISSION_GRANT) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openAlbum();
            } else {
                Toast.makeText(DrawActivity.this, "请授予文件访问权限", Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CHOOSE_IMAGE && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            Log.d("Tianma", "Uri = " + uri);
            String path = ImageUtils.getRealPathFromUri(this, uri);
            Log.d("Tianma", "realPath = " + path);
            Bitmap bm = ImageUtils.decodeSampledBitmapFromDisk(path, width, height);

            double wb = 1.0, hb = 1.0;

            if (bm.getWidth() > width || bm.getHeight() > height) {
                if (bm.getWidth() - width > bm.getHeight() - height) {
                    wb = width * 1.0 / bm.getWidth();
                    hb = width * 1.0 / bm.getWidth();
                } else {
                    wb = height * 1.0 / bm.getHeight();
                    hb = height * 1.0 / bm.getHeight();
                }
            }

            double leftR = (width - bm.getWidth() * wb) / 2;
            double topR = (height - bm.getHeight() * hb) / 2;

            mCv.drawBitmap(bm, null, new Rect((int) leftR, (int) topR, (int) (leftR + bm.getWidth() * wb), (int) (topR + bm.getHeight() * hb)), mPt_Fill);
            saveHis();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "SimplePainter");
        if (!appDir.exists()) {
            //noinspection ResultOfMethodCallIgnored
            appDir.mkdir();
        }
        String fileName = "sp-" + System.currentTimeMillis() + ".png";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
    }
}
